package com.ruoyi.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.ruoyi.common.core.utils.file.QiniuUtils;
import com.ruoyi.system.config.AppConfig;
import com.ruoyi.system.domain.PetType;
import com.ruoyi.system.domain.PetVariety;
import com.ruoyi.system.domain.dto.ImageSynthesisRequest;
import com.ruoyi.system.mapper.PetTypeMapper;
import com.ruoyi.system.mapper.PetVarietyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.system.mapper.PetMapper;
import com.ruoyi.system.domain.Pet;
import com.ruoyi.system.domain.dto.PetRecognitionResult;
import com.ruoyi.system.service.IPetService;

import javax.imageio.ImageIO;

/**
 * 宠物服务实现类
 */
@Service
public class PetServiceImpl implements IPetService {
    @Autowired
    private PetMapper petMapper;


    private static final List<String> CONTEXT_TYPES = Arrays.asList("image/jpeg","image/png","image/jpg","image/gif");

    @Value("${pet.recognition.url:https://api.example.com/recognize}")
    private String recognitionUrl;

    @Value("${pet.recognition.key:your_api_key}")
    private String apiKey;

    @Autowired
    private PetTypeMapper petTypeMapper;
    @Autowired
    private PetVarietyMapper petVarietyMapper;

    @Override
    public List<Pet> selectPetList(Pet pet) {
        return petMapper.selectPetList(pet);
    }

    @Override
    public Pet selectPetById(Long id) {
        return petMapper.selectPetById(id);
    }

    @Override
    public int insertPet(Pet pet) {
        return petMapper.insertPet(pet);
    }

    @Override
    public int updatePet(Pet pet) {
        return petMapper.updatePet(pet);
    }

    @Override
    public int deletePetById(Long id) {
        return petMapper.deletePetById(id);
    }

    @Override
    public int deletePetByIds(Long[] ids) {
        return petMapper.deletePetByIds(ids);
    }

    @Override
    public PetRecognitionResult recognizePet(MultipartFile file) {
        try {
            // 1. 验证文件
            if (file == null || file.isEmpty()) {
                return PetRecognitionResult.error("请选择要识别的图片文件");
            }

            // 2. 验证文件类型
            String contentType = file.getContentType();
            if (!CONTEXT_TYPES.contains(contentType)) {
                return PetRecognitionResult.error("不支持的图片类型，仅支持jpg、jpeg、png、gif格式");
            }

            // 3. 上传文件并获取URL
            String uploadFile = this.uploadFile(file);
            System.out.println("宠物识别是上传的图片"+uploadFile);
            if (uploadFile.equals("错误的图片") || uploadFile.equals("图片内容不合法")) {
                return PetRecognitionResult.error(uploadFile);
            }

            // 4. 准备请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 5. 准备请求参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("key", apiKey);
            params.add("imgurl", uploadFile);

            // 6. 发送请求
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            ResponseEntity<PetRecognitionResult> response = AppConfig.restTemplate().postForEntity(
                recognitionUrl,
                requestEntity,
                PetRecognitionResult.class
            );

            // 7. 处理响应
            if (response.getStatusCode() == HttpStatus.OK) {
                PetRecognitionResult result = response.getBody();
                if (result == null) {
                    return PetRecognitionResult.error("识别服务返回结果为空");
                }
                return result;
            } else {
                return PetRecognitionResult.error("宠物识别服务调用失败，HTTP状态码：" + response.getStatusCode());
            }
        } catch (Exception e) {
            return PetRecognitionResult.error("宠物识别服务调用异常: " + e.getMessage());
        }
    }


    //上传图片方法
    @Override
    public String uploadFile(MultipartFile file) {
        //图片的类型
        try {
            String newFilename = null;
            String contentType = file.getContentType();
            if(!CONTEXT_TYPES.contains(contentType)){
                return "错误的图片";
            }

            // 使用try-with-resources确保流被正确关闭
            try (InputStream inputStream = file.getInputStream()) {
                BufferedImage read = ImageIO.read(inputStream);
                if(read == null){
                    return "图片内容不合法";
                }
                String filename = file.getOriginalFilename();
                int i = filename.lastIndexOf(".");
                String substring = filename.substring(i);
                String s = UUID.randomUUID().toString().replace("-", "");
                newFilename = s + substring;
                // 使用字节数组而不是直接使用输入流
                QiniuUtils.upload2Qiniu(file.getBytes(), newFilename);
                return "http://subufxkbf.hb-bkt.clouddn.com/" + newFilename;
            }
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } finally {
            // 手动触发垃圾回收，帮助释放文件句柄
            System.gc();
        }
    }

    @Override
    public List<PetType> getType() {
        return petTypeMapper.getType();
    }

    @Override
    public List<PetVariety> getPetVariety(Integer tId) {
        return petVarietyMapper.getPetVariety(tId);
    }

    @Override
    public Pet getPetInfo(Integer uid) {
        return petMapper.selectPetListByUid(uid);
    }

    @Override
    public Object recognizeEmotion(MultipartFile file) {
        try {
            // 1. 验证文件
            if (file == null || file.isEmpty()) {
                return PetRecognitionResult.error("请选择要识别的图片文件");
            }

            // 2. 验证文件类型
            String contentType = file.getContentType();
            if (!CONTEXT_TYPES.contains(contentType)) {
                return PetRecognitionResult.error("不支持的图片类型，仅支持jpg、jpeg、png、gif格式");
            }

            // 3. 上传文件并获取URL
            String uploadFile = this.uploadFile(file);
            System.out.println("宠物识别是上传的图片"+uploadFile);
            if (uploadFile.equals("错误的图片") || uploadFile.equals("图片内容不合法")) {
                return PetRecognitionResult.error(uploadFile);
            }

            MultiModalConversation conv = new MultiModalConversation();
            MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                    .content(Arrays.asList(
                            Collections.singletonMap("image", uploadFile),
                            Collections.singletonMap("text", "分析宠物情绪"))).build();
            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // 此处以qwen-vl-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                    .model("qwen-vl-plus")
                    .message(userMessage)
                    .build();
            MultiModalConversationResult result = conv.call(param);
            System.out.println(JsonUtils.toJson(result));
            return JsonUtils.toJson(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object imageSynthesis(MultipartFile baseImage, MultipartFile maskImage, String prompt) {
        return null;
    }

    @Override
    public PetType getPetTypeById(Long tId) {
        return petTypeMapper.getPetTypeById(tId);
    }

    @Override
    public PetVariety getPetVarietyById(Long vId) {
        return petVarietyMapper.getPetVarietyById(vId);
    }


}
